package application

import java.io.ByteArrayInputStream
import java.net.{URI, URL}
import java.util
import javax.imageio.ImageIO

import DB._
import com.redis._
import controllers._
import org.apache.http.client.methods.HttpRequestBase
import play.api.Logger
import tools._
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
import scala.concurrent._
import ExecutionContext.Implicits.global
import common._
import common.Tool._
import java.util.{UUID, Date}


import scala.util.Random
import scala.xml.XML

object Example {

  def main(args: Array[String]): Unit = {
    reTry(1){
      println("a")
      throw new Exception("你妹的异常")
    }
//    val list=1 to 10 toList
//
//    println(list.take(3))
//    println(list.drop(3))
//    println(UUID.randomUUID().toString.replace("-",""))
//
//    println("admin".encrypt())
//    println("abcdg".toCharArray.mkString(","))
//    import common.TimeTool._
//      val article=new UserArticle().query(s"status=5")
//    println(article.size)
//    println(article.map(_.aid).toSet.mkString(","))
//    val oa=new Article().query(s"id in(${article.map(_.aid).toSet.mkString(",")})").map(v=>v.id->v).toMap
//    var count=0
//    article.filter(_.contentPath.isEmpty).mutile(2).foreach{a=>
//      count+=1
//      new UserArticle(a.id,contentPath =oa(a.aid).contentPath ).update("id","contentPath")
////      println(a.toJson)
//      println(count)
//       NetTool.HttpGet("http://www.handuser.com/api/mobile/see/"+a.id)
//    }

//    val url="http://wx.handuser.com/html/d4ea6a96d7094754bb3f16e8f7f5ce4c.html?t=70296"
//    println(url.split("/").last.split("\\?").head.dropRight(5))
//    val (num,size)=(2,5)
//    println(List(1,2,3,4,5,6,7,8,9,10).drop((num-1)*size).take(size))
//    println("""vid":"h01633wble5"""".dropRight(1).drop(6))
//    System.exit(0)
////
//    val settings = new Setting().queryAll map {
//      s =>
//        s.name -> s.value
//    } toMap //设置
//
//    if(settings.size >0 )  Tool.setCache(SETTING_VALUE_CACHE_KEY, settings,3600)
//
//    val fs=getSettingCacheObject("aliAccessId", "aliAccessKey","aliOssBucket","aliOssaliyunEndpoint","aliOssHost")(list => new Aliyun(list(0), list(1),list(2),list(3),list(4)))
//    val name="html/5c6135e1c16b416d844f30179e8330c4.html"
//    val data=fs.getFile(name).get
//    val jsoup=Jsoup.parse(new String(data,"utf-8"))
//    jsoup.body().append(
//      """
//        |
//        |
//        |<script id="qqmusic_tpl" type="text/html">
//        |        <span id="qqmusic_main_<#=comment_id#>_<#=posIndex#>" class="db qqmusic_area <#if(!musicSupport){#> unsupport<#}#>">
//        |            <span class="tc tips_global unsupport_tips" <#if(show_not_support!==true){#>style="display:none;"<#}#>>
//        |            当前浏览器不支持播放音乐或语音，请在微信或其他浏览器中播放            </span>
//        |            <span class="db qqmusic_wrp">
//        |                <span class="db qqmusic_bd">
//        |                    <span id="qqmusic_play_<#=musicid#>_<#=posIndex#>" class="play_area">
//        |                        <i class="icon_qqmusic_switch"></i>
//        |                        <img src="http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/qqmusic/icon_qqmusic_default.2x26f1f1.png" alt="" class="pic_qqmusic_default">
//        |                        <img src="<#=music_img#>" data-autourl="<#=audiourl#>" data-musicid="<#=musicid#>" class="qqmusic_thumb" alt="">
//        |                    </span>
//        |                                        <a id="qqmusic_home_<#=musicid#>_<#=posIndex#>" href="javascript:void(0);" class="access_area">
//        |                        <span class="qqmusic_songname"><#=music_name#></span>
//        |                        <span class="qqmusic_singername"><#=singer#></span>
//        |                        <span class="qqmusic_source"><img src="http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/qqmusic/icon_qqmusic_source263724.png" alt=""></span>
//        |                    </a>
//        |                </span>
//        |            </span>
//        |        </span>
//        |    </script>
//        |
//      """.stripMargin)
//    println(jsoup.outerHtml())
//    fs.saveFile(name,data,"text/html; charset=utf-8")

    //    val users=new User().queryAll().map(_.id).toSet
//    val sets=new UserSetting().queryAll().map(_.id).toSet
//    users.map{
//      u=>
//        if(!sets.contains(u)){
//          UserController.appendUserIcon(u)
//        }
//    }
//    val iconsList=settings("usericons").jsonToHashMap("icons").asInstanceOf[List[Map[String,AnyRef]]]
//    val sets=new UserSetting().queryAll()
//    sets.map { s =>
//      val data = s.exts.jsonToHashMap
//      if (data.contains("icons") && data("icons").asInstanceOf[List[Map[String, AnyRef]]].size < 10) {
//        val iconsSet=new mutable.HashSet[String]
//        val saveiconsList=new ArrayBuffer[Map[String, AnyRef]]
//
//        data("icons").asInstanceOf[List[Map[String, AnyRef]]] ::: iconsList foreach{m=>
//          if(!iconsSet.contains(m("url").toString)){
//            saveiconsList.append(m)
//            iconsSet.add(m("url").toString)
//          }
//        }
//        data("icons") = iconsList.toList
////        if(s.id==6) {
//          new UserSetting(s.id, data.toJson).update("id", "exts")
////        }
//      }
//      if (!data.contains("icons")) {
//        data("icons") = iconsList
////        if(s.id==798) {
//          new UserSetting(s.id, data.toJson).update("id", "exts")
////        }
//      }
//    }


//    UserController.appendUserIcon(167)
//
//    ArticleController.updateStat

    //def cloopenSms = getSettingCacheObject("cloopenAccount", "cloopenToken", "cloopenAppid")(list => new Cloopen(list(0), list(1), list(2)))
//    def cloopenSms = new Cloopen("aaf98f894ac8352e014accfb139502a3","4683b78edc854b4e9355912c90f57c32","aaf98f894ac8352e014acd5fd0520334")
//    cloopenSms.sendTempSms("17092848584","14823","12345")


    //    println(Random.nextInt(10000))
//    val html="""{"pay_status":8,"episode_updated":null,"is_trailer":0,"year":"","director":null,"title":"【舞槑娘】火辣美腿の舞蹈练习室","cover_id":"dvg3ze6zppsvr0i","outsite_flag":null,"publish_date":null,"second_title":"【舞槑娘】火辣美腿の舞蹈练习室","video_ids":["i01748iyeh3","d0174al5l9y","m0173kzl0oc","e01736mjnq6","g0174nkpc32","h0174vi13ow","u0174cjswb7","s0173ljdcpr","u01726z9e3p","e0172egqogb","e01726y7ego","o01733bbs4c","v01724v0tjd","y0172tdilry","i0171bvrluq","e0170dypmn0","g01714aijdn","i0169lnhjps","w01675iy93u","q0167p3i64a","w01666qztwm","a0167enddb6","c0165x95kfp","b0165wx31w7","n0167elpqt8","j0163l9o81z","j0162wcyrg8","n0161g3gykp","l0161hzg6x7","o0161xamw1r","n0161b4o00c","y0161daifyr","q01609axqnz","x0160mz8cwz","o0160i769q6","a016016xzr4","b016039gs5q","t0159crf1ip","s015931ctgd","d0159ib3we9","a0159kng1ot","u015799lal4","u0159xtb6io","v01599z6fp3","d0157tte3bn","j0157yxa3jt","l0157uo7dir","h01565wfsh0","c015601nqyd","d015735ixej","u0156t6txgx","u0156u0aa2u","l0156ngz2lz","s0156lnuijf","g0156gih1yj","a0156zh58hm","z0156ei4104","p0155e1o53q","b0155agzldr","t0155laju5r","e0155i8am64","a0154ymd525","e0153pzzkou","p0153h8eyh5","a0153vbi6da","i01528ti8w3","c01564zg0qf","o0152i83rqa","e0152thnifi","l0152sguyw6","w0151w2k09f","h0151cewj3c","m0151005f4t","b0152vgdejs","g0151lrmsk3","o0151k3ebjk","e01516px35s","x0151k7t1ps","g0151pb6ygm","n0151xt40u6","w0151sbvew6","o01519636pa","y01519wok1h","y0174hskjl8"],"column_id":0,"horizontal_pic_url":"http://i.gtimg.cn/qqlive/img/jpgcache/files/qqvideo/hori/d/dvg3ze6zppsvr0i.jpg","leading_actor_id":null,"category_map":[10761,"MV",1125,"MV",22,"音乐"],"downright":["1","2","3","4","5","8"],"vertical_pic_url":"http://i.gtimg.cn/qqlive/img/jpgcache/files/qqvideo/d/dvg3ze6zppsvr0i.jpg","leading_actor":[],"playright":["1","2","3","4","5","8"],"episode_all":null,"type":22,"cover_checkup_grade":4,"area_name":"","giftbag_id":null,"real_exclusive":"0","update_desc":"","description":"【舞槑娘】火辣美腿の舞蹈练习室","subtype":[]}"""
//    val v=getExpr(html,"video_ids","]",null).map(_.substring(11))
//    println(List().toBean(v.getOrElse("[]")))
//    val url="http://m.v.qq.com/cover/u/ufucm8dqdftoh58.html?vid=x00196bdvy1"
//    val vid=url.drop(url.indexOf("?")+1).split("&").filter(_.contains("vid")).head.split("=")(1)
//    println(vid)
//   val v=TimeTool.parseStringToDate("2010-01-01").getTime()
//    println(v+"")

//    val key="ad.top[2]"
////    val v=key.split("\\.")
////    println(v)
//    val data="""{"ad":{"top":["123","234","345"]}}"""
//    val value=UtilController.getExtByExp(data,key,"ad.bottom")
//    println(value)
//    println(key.substring(key.indexOf("[")+1,key.indexOf("]")))
//    val url="http://mp.weixin.qq.com/s?__biz=MzI5OTAxOTcxMA==&mid=400184962&idx=1&sn=b50662dc482a9792f8126f6a495924a0&scene=1&srcid=1028dn5enVSsHxLBDgoZWW0o&from=groupmessage&isappinstalled=0#wechat_redirect"
//      val ns=new NodeContentServer("http://127.0.0.1:3000")
//    println(ns.extractContent(url))

//    println(WEBRule.handle("http://m.v.qq.com/cover/x/xfxd9mej2luhfoz.html"))

//    val v = "你妹"
//    JedisTool.useJedis(_.set("a", v))
//    println(JedisTool.useJedis(_.get("a")))
//    assert(v == JedisTool.useJedis(_.get("a")).get)
//    JedisTool.useJedis(_.expire("a", 5))
//    Thread.sleep(6000)
//    assert(!JedisTool.useJedis(_.exists("a")))

//    val c=NetTool.wrapClient(NetTool.getHttpClient(true))
//    val v=c.execute(new HttpPURGE("http://www.rechuan0991.com/mobile/article/ade52cab8a6e407cb7c4044b4d02318c"))
//
//      println(v)

//    val url="http://code.taobao.org/p/OceanBase/wiki/intro/2345675432"
//    println(url.size - url.lastIndexOf("/"))
//    println(url.takeRight(url.size - url.lastIndexOf("/")-1))

//    val id = url.takeRight(url.size - url.lastIndexOf("/") - 1)
//    val newurl=url.take(url.lastIndexOf("/"))
//    val aid= newurl.takeRight(newurl.size - newurl.lastIndexOf("/") - 1)
//    println(id)
//    println(aid)

//    println(new Setting().queryAll().toJson)

//    JedisTool.getJedis.subscribe("cache") { msg =>
//      msg.toJson
////      println(msg.toJson)
//      msg match {
//        case M(channel, message) =>
//          println(channel + ","+message)
//        case _ =>
//      }
//    }
////    Thread.sleep(1000)
//    val v=JedisTool.useJedis(_.publish("cache","你妹的id"))
//    println(v)
//    0 to 100 foreach{i=>
//      println("-----------------------")
//      Thread.sleep(1000)
//    }



//    val topads = new ShareArticleAd().query("id=?", "3405f1f929c54c63b8d6d65013e8c9cd").head
//    val bottomads = new ShareArticleAd().query("id=?", "b3a57484472346718d4a818aeedf6d88").head
//    //跨表更新数据
//    DBEntity.chargeDB("mysql"){
//      topads.insertWithId()
//    }{ex=>
//      ex.printStackTrace()
//    }
//    DBEntity.chargeDB("mysql"){
//      bottomads.insertWithId()
//    }{ex=>
//      ex.printStackTrace()
//    }
//      println(NetTool.HttpGet("http://www.handka.com:9011/api/platform/syncStatistics/")._2)
//    println("asfasfd data-src=sfsfa".replaceAll("data-src","src"))
//      println(QrcodeTool.parseCodeByUrl("http://mmbiz.qpic.cn/mmbiz/jriakQUZeJdicbic1JTiaGOf4zPSrW3sX90Oib3Ot1YDT0oXUzE9beX4j6EFcQY6iaoibuIStn73iaib8VPJfcYmoIzjdjA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1"))
//      val url="http://mmbiz.qpic.cn/mmbiz/jriakQUZeJdicbic1JTiaGOf4zPSrW3sX90Oib3Ot1YDT0oXUzE9beX4j6EFcQY6iaoibuIStn73iaib8VPJfcYmoIzjdjA/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1"
//    val httpv=  NetTool.HttpGetBin(url,appendHead =  Map("User-Agent"->WEBEngine.ua,"Host"->"mmbiz.qpic.cn"))._2
//    val v=ImageIO.read(new ByteArrayInputStream(httpv))
//
//    val source = new BufferedImageLuminanceSource(v)
//    val bitmap = new BinaryBitmap(new HybridBinarizer(source))
//    //解码设置编码方式为：utf-8，
//    val result = new MultiFormatReader().decode(bitmap)
//    val resultStr = result.getText()
//    println("解析后内容："+resultStr)

//    println("123456".md5())
//    println("123456".md5())
//    println(0 until 10)
//      val wx=new WeiXin("232342","fdgsdgdrt546456","32523423")
//    val xml="""<xml>
//              |   <return_code><![CDATA[SUCCESS]]></return_code>
//              |   <return_msg><![CDATA[OK]]></return_msg>
//              |   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
//              |   <mch_id><![CDATA[10000100]]></mch_id>
//              |   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
//              |   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
//              |   <result_code><![CDATA[SUCCESS]]></result_code>
//              |   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
//              |   <trade_type><![CDATA[JSAPI]]></trade_type>
//              |</xml>
//              | """.stripMargin
//    val parseXml=XML.loadString(xml)
//    val data=parseXml.child.map(v=>v.label-> v.text).filter(!_._2.trim.isEmpty).toMap
//    println(data.toJson)
//
//    println(wx.checkSignWxPay(data))
//    val v=new WeiXin("232342","fdgsdgdrt546456","32523423").rechargeWxPay("afdsf","545sdfsef",100,"8.8.8.8","")
//      println(v.toJson)
//    val v=JedisTool.hmget(USER_USERNAME_CACHE_KEY,"1"::"2"::Nil toArray)
//    println(v)
//    val v=PlaceTool.getPlaceIdsFastByLocation(new Location(0,30.5785,103.9973,5000))
//    println(v.toJson)
//    println(getAfterDate("-1M").sdate)
    //    def getIpFromString(ipstr:String)={
    //      val arr=ipstr.split("\\.").map(_.toLong)
    //      (arr(0) << 24) + (arr(1) << 16) + (arr(2) << 8) + arr(3);
    //    }
    //    def getIpFromLong(ip:Long)={
    //      val list=(ip >>> 24) :: ((ip & 0x00FFFFFF) >>> 16) ::((ip & 0x0000FFFF) >>> 8) ::(ip & 0x000000FF) ::Nil
    //      list.mkString(".")
    //    }
    //    val f=getIpFromString("127.0.0.1")
    //    println(f)
    //    println(getIpFromLong(f))
    //      exit(0)
    //      val list:ListBuffer[String]=new ListBuffer()
    //      list append "a"
    //      list append "b"
    //      list append "c"
    //    val b=list.filter(_ != null)
    //      list.clear()
    //    println(b)
    //    println(list)
    //      println(TimeTool.getFormatStringByDate(TimeTool.getAfterDate("1M",new Date(114,0,30))))
    //    println(toBean("""{"borrow_1_1405320165368_0.jpg":"身份证","borrow_1_1405320165368_1.jpg":"身份证反面"}""",classOf[Map[String,String]]))
    //    val assureScale=JedisTool.hget(ASSURE_SCALE_CACHE_KEY,"1",{id=>
    //      val userext=new UserExtInfo().queryById(1).get
    //      userext.assureScale.toString
    //    }).toDouble
    //    println(assureScale)
    //    JedisTool.hset(ASSURE_SCALE_CACHE_KEY,"1","1")
    /* println(TimeTool.getDayDiff(new Date(2014-1900,5,23),new Date(2014-1900,5,22)))
     exit(0)
     DBEntity.sql(s"update ${new UpdateUser().tableName} set lockMoney = lockMoney - ? ,borrowOut =borrowOut + ? where id=?",20.toString,20.toString,1.toString)
     exit(0)*/
    //    new UpdateBid().createTable()
    //    new Bid(0,1,100,1,0,new Date()).insert()
    //    new Bid(0,2,100,1,0,new Date()).insert()
    //    new Bid(0,1,300,1,0,new Date()).insert()
    /** ***********************xdj  start ****************************/
    //    val a=Array("sms","wx")
    //    println(a.contains("sm"))
    /** ***********************xdj  end ****************************/
    //初始化连接
    //    DBEntity.setDataSource("com.mysql.jdbc.Driver","icdDba","icdDba","jdbc:mysql://192.168.2.4:3303/inChengdu3")
    //    println(new User(0,"livehl","子轩","livehl@126.com").createTable())
    /*    TimeTool.calTimeUse{any=>
          val user=DBCacheTool.getDBData(classOf[Setting],"1")*/
    //      println(user.toString)
    //   }
    /*    TimeTool.calTimeUse{any=>
          val user=DBCacheTool.getDBData(classOf[Setting],"1")
          //      println(user.toString)
        }
        exit(0)*/
    //查询
    /*    val user=DBEntity.queryOne(classOf[User],"select * from User where username=? ","livehl")
        println(user)
        exit()*/
    //    val users=DBEntity.query(classOf[CaseUser], "select * from User limit 10")
    //    println(users)

    //插入
    //    val id=new User(0,"livehl","子轩","livehl@126.com").insert() // id=1,name=tom,age=12
    //    println(id)
    //    val id1=new User(0,"livehl1","子轩1","livehl@123.com").insert("username") //id=2,name=tomcat,age=null
    //    println(id1)
    //更新
    //    val newUser=DBEntity.queryById(classOf[User], "User", id).get
    //    println(DBEntity.queryById(classOf[CaseUser], "User", id).get)
    //    newUser.nickname="livehl2"
    //    newUser.update("id", "nickname")
    //    println(DBEntity.queryById(classOf[CaseUser], "User", id).get)

    //删除
    //    new User(id,"","","").delete("id")
    //
    //    new User(id1,"","","").delete("id")


  }

}


//class HttpPURGE(url:String) extends HttpRequestBase {
//  val METHOD_NAME: String = "PURGE"
//
//  setURI(URI.create(url))
//
//  def getMethod: String = {
//    return METHOD_NAME
//  }
//}